<template>
  <div class="customer-form">
    <el-card>
      <h2>{{ isEdit ? '编辑客户' : '新增客户' }}</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="max-width:500px;">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="contactEmail">
          <el-input v-model="form.contactEmail" />
        </el-form-item>
        <el-form-item label="行业" prop="industryType">
          <el-input v-model="form.industryType" />
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-input v-model="form.source" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option :value="1" label="活跃" />
            <el-option :value="0" label="非活跃" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addCustomer, updateCustomer, getCustomer } from '@/api/customer'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const isEdit = ref(false)
const form = ref({
  customerName: '',
  contactPhone: '',
  contactEmail: '',
  industryType: '',
  source: '',
  status: 1,
  remark: ''
})
const rules = {
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
}

onMounted(async () => {
  if (route.params.id) {
    isEdit.value = true
    const res = await getCustomer(route.params.id)
    Object.assign(form.value, res)
  }
})

const handleSubmit = async () => {
  await formRef.value.validate()
  if (isEdit.value) {
    await updateCustomer(form.value)
    ElMessage.success('修改成功')
  } else {
    await addCustomer(form.value)
    ElMessage.success('新增成功')
  }
  router.push('/customers')
}
const goBack = () => router.push('/customers')
</script>

<style scoped>
.customer-form {
  padding: 32px 0;
}
</style> 